'''
基于tif生成mask的 histocis 格式的 json

目标 histomics mask 格式
{
  "_accessLevel": 0,
  "_modelType": "annotation",
  "annotation": {
    "description": "",
    "elements": [
      {
        "group": "mostly_lymphocytic_infiltrate",
        "closed": true,
        "label": {
          "value": "mostly_lymphocytic_infiltrate"
        },
        "points": [
          [38074, 25643, 0],
        ],
        "fillColor": "rgba(0,0,255,0.5)",
        "lineColor": "rgb(0,0,255)",
        "lineWidth": 2,
        "type": "polyline"
      },
    ]
  }
}
'''
import copy
import json
import os
import cv2
import pyvips
import numpy as np
from matplotlib import pyplot as plt


def show_array(arr):
    plt.figure()
    ax = plt.gca()
    # 逐一绘制坐标点，并使用下标作为标签
    for i, (x, y) in enumerate(arr):
        # 绘制点
        ax.plot(x, y, label='Lines', linestyle='-', color='blue', linewidth=2)
        # 添加标签（使用下标i+1，因为通常我们从1开始计数）
        ax.text(x, y, str(i + 1), ha='center', va='center', fontsize=10)
        # 显示图形
    plt.show()


geo_json = '{"annotation":{"elements":[],"name":""}}'
his_obj = json.loads(geo_json)
elements_json = '{"type":"polyline","points":[],"fillColor":"rgba(255,0,0,0.5)","lineColor":"rgb(255,0,0)","lineWidth":2, "closed": true}'
element_obj = json.loads(elements_json)

tif_folder_path = "/home/hsmy/桌面/微浸润结果case/tif"
target_path = "/home/hsmy/桌面/微浸润结果case/mask_his/"
if not os.path.exists(target_path):
    os.makedirs(target_path)
# 遍历指定文件夹下的所有文件
for root, dirs, files in os.walk(tif_folder_path):
    for file in sorted(files):
        try:
            file_path = os.path.join(root, file)
            slide = pyvips.Image.openslideload(file_path, level=3)
            slide_arr = np.array(slide)[..., 0]
            target_arr = (slide_arr == 1) + (slide_arr == 3) + (slide_arr == 4)
            elements = []
            # 使用OpenCV的findContours函数找到所有连通域的边界
            contours, _ = cv2.findContours(np.array(target_arr, dtype=np.uint8), cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_TC89_L1)
            # 遍历每个标记的连通域，记录其坐标
            for i, contour in enumerate(contours):
                points = []
                if len(contour) < 10:
                    continue
                contour = contour.reshape(-1, 2)
                # show_array(contour)
                for point in contour:
                    x = int(point[0] * 64)
                    y = int(point[1] * 64)
                    points.append([x, y, 0])
                element = copy.deepcopy(element_obj)
                element['points'] = points
                elements.append(element)

            v = copy.deepcopy(his_obj)
            v['annotation']['elements'] = elements
            file_name = target_path + file.split('.')[0] + '_mask.json'
            v['annotation']['name'] = file.split('.')[0] + '_mask'
            with open(file_name, "w") as file_:
                json.dump(v, file_)
        except json.JSONDecodeError as e:
            print(f"Error decoding JSON file: {e}")
